﻿using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;

namespace Infrastructure
{
    public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged
    {
        [Dependency]
        public IUnityContainer UnityContainer { get; set; }

        [Dependency]
        public IRegionManager RegionManager { get; set; }

        [Dependency]
        public IEventAggregator EventAggregator { get; set; }


        protected void OnPropertyChanged<T>(Expression<Func<T>> action)
        {
            var expression = action.Body as MemberExpression;
            string propertyName = expression.Member.Name;

            OnPropertyChanged(propertyName);
        }

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void AddViewModel(string regionName)
        {
            ClearViewModel(regionName);
            AddViewModel(this, regionName);
        }

        protected void AddViewModel(ViewModelBase viewModel, string regionName)
        {
            IRegion region = RegionManager.Regions[regionName];
            if (region != null)
            {
                region.Add(viewModel,viewModel.GetType().ToString());
            }
        }

        protected void ClearViewModel(string regionName)
        {
            IRegion region = RegionManager.Regions[regionName];
            if (region != null)
            {
                foreach (var item in region.Views)
                {
                    region.Remove(item);
                }
            }
        }

        protected void RemoveViewModel(ViewModelBase viewModel, string regionName)
        {
            IRegion region = RegionManager.Regions[regionName];
            if (region != null)
            {
                region.Remove(viewModel);
            }
        }

        abstract protected void Substrict();

        abstract protected void UnSubstrict();
    }
}
